<script setup>
import { ref,watch,reactive } from 'vue';
import { ElMessage, ElTag } from 'element-plus';
import { useRouter } from 'vue-router';
import { brandQueryPage,insertSave,deleteById,updateById} from '@/api/brand';


const router = useRouter(); // 获得路由对象
const searchQuery = ref('');
// 请求参数数据模型
const queryPageParam = ref({
  pageNum: 1,
  pageSize: 5, 
  bname:"",
  bsex:""
 
});
const isEdit = ref(false); // 区分操作类型：false=新增，true=修改
const form = ref({
  bname: '',    // 品牌名称
  bsex: '',     // 鞋类性别（男/女）
  bstate: '0',  // 是否上线（默认未上线，对应0）
  bremarks: ''  // 品牌备注
});
const showModal = ref(false); // 新增弹窗显示状态
// 2. 表单ref：用于表单验证和重置
const brandForm = ref(null);

const statusOptions = [// 下拉列表选项（从步骤1引入或直接定义）
  { label: "", value: '' },
    { label: "男", value: '男' },
    { label: "女", value: '女' },
];
const formRules = reactive({// 表单验证规则：确保必填字段不为空
  bname: [
    { required: true, message: '请输入品牌名称', trigger: 'blur' },
    { min: 2, max: 50, message: '品牌名称长度需在2-50字符之间', trigger: 'blur' }
  ],
  bsex: [
    { required: true, message: '请选择鞋类性别', trigger: 'change' }
  ],
  bstate: [
    { required: true, message: '请选择是否上线', trigger: 'change' }
  ],
  bremarks: [
    { max: 200, message: '备注长度不能超过200字符', trigger: 'blur' }
  ]
});

const brandList = ref([]);

// 5. 点击“新增品牌”按钮：打开弹窗并重置表单
const handleAddbrand = () => {
  // 重置表单（清空数据+清除验证状态）
  if (brandForm.value) {
    brandForm.value.resetFields();
  }
  // 打开弹窗
  showModal.value = true;
};
// 修改品牌按钮点击（接收当前行数据）
const handleEdit = (row) => {

  isEdit.value = true; // 标记为修改
   resetForm(); // 重置表单
  // 填充当前行数据到表单（注意类型转换）
  form.value.bid = row.bid;
  form.value.bname = row.bname;
  form.value.bsex = row.bsex;
  form.value.bstate = row.bstate.toString(); ; // 转为字符串匹配radio的label
  console.log("form.value.bstate:",form.value.bstate)
  form.value.bremarks = row.bremarks || ''; // 处理null值
  showModal.value = true; // 打开对话框
};

// 重置表单
const resetForm = () => {
  if (brandForm.value) {
    brandForm.value.resetFields();
  }
  // 清空表单数据（保留默认值）
  form.bid = '';
  form.bname = '';
  form.bsex = '';
  form.bstate = '0';
  form.bremarks = '';
};

const handClose = () => {
  if (brandForm.value) {
    brandForm.value.resetFields();
  }
  showModal.value = false;
};

// 7. 保存品牌：表单验证通过后调用新增接口
const saveBrand = async () => {
  if (!brandForm.value) return;
  try {
    await brandForm.value.validate(); // 触发表单验证
    await insertSave(form.value)
      ElMessage.success('商标新增成功');
      handClose(); // 关闭弹窗
      handleSearch()

  } catch (error) {
    // 验证失败：提示用户完善信息
    ElMessage.warning('请完善必填字段后再提交');
    ElMessage.error('品牌新增失败，请重试');
    
    return;
  }
};
// 修改品牌提交
const updateBrand = async () => {
  try {
    await brandForm.value.validate();
    await updateById(form.value)
    ElMessage.success('品牌修改成功！');
    handClose();
    handleSearch()// 刷新列表
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('修改失败：' + (error.message || '未知错误'));
    }
  }
};

// 请求订单函数
function querybrand() {
  brandQueryPage(queryPageParam.value.bsex,queryPageParam.value.bname,queryPageParam.value.pageNum, 
  queryPageParam.value.pageSize)
    .then(data => {
      // 将数据赋值给数据模型
      brandList.value = data.list || [];
      // 假设接口返回的分页信息包含总记录数
      queryPageParam.value.recordCount = data.pager?.recordCount || 0;
      console.log(brandList, queryPageParam)
    })
    .catch(error => {
      ElMessage.error('获取订单列表失败：' + (error.message || '未知错误'));
    });
}




// 1. 防抖定时器（用于清除上一次的延迟查询）
let searchTimer = null;
// 4. 防抖搜索核心函数  增加 immediate 参数（默认 false）
const debounceSearch = async (immediate = false) => {
  // 第一步：清除上一次的定时器（防止重复触发）
  if (searchTimer) {
    clearTimeout(searchTimer);
  }

// 定义核心查询逻辑（抽成函数，避免重复代码）
  const doSearch = async () => {
    try {
      // 重置页码（搜索时从第1页开始）
      queryPageParam.value.pageNum = 1;
      // 赋值搜索参数
      const searchVal = searchQuery.value.trim();
      queryPageParam.value.bname = searchVal;
      
      // 发起请求（await 等待结果）
        querybrand();

    } catch (err) {
      ElMessage.error('查询失败，请重试');
      console.error('搜索错误：', err);
    }
  };

  // 关键逻辑：根据 immediate 决定是否立即执行
  if (immediate) {
    // 手动触发：立即执行查询（无延迟）
    await doSearch();
  } else {
    // 自动输入：延迟 500ms 执行（防抖）
    searchTimer = setTimeout(doSearch, 500);
  }
};

    // 5. 监听输入框变化，自动触发防抖搜索
    watch(searchQuery, (newVal) => {
      // 输入变化时，立即执行防抖逻辑
      debounceSearch();
    }, {
      immediate: true // 初始加载时，若 searchQuery 有默认值，也触发一次查询
    });

// 搜索订单
const handleSearch = () => {
  debounceSearch(true); // 手动触发 → 立即执行
};

// 表格行样式
const tableRowClassName = ({ row, rowIndex }) => {
  return rowIndex % 2 === 0 ? 'table-row-even' : 'table-row-odd';
};

// 行点击事件
const handleRowClick = (row) => {
  console.log('点击了行:', row);
  // 可以在这里实现点击行查看详情等功能
};



const handleDelete = async (id) => {
  try {
    console.log("执行了 删除")
    await deleteById(id);
    handleSearch()
  } catch (error) {
    console.error('删除失败:', error);
  }
};

</script>

<template>
  <div class="brand-management-container">
    <!-- 页面标题区域 -->
    <div class="page-header">
      <h1>品牌管理中心</h1>
      <p>查看和管理所有品牌信息，支持筛选、编辑和删除操作</p>
    </div>

    <!-- 品牌表格卡片 -->
    <el-card class="brand-table-card">
      <!-- 表格工具栏 -->
      <div class="table-toolbar">
        <el-input 
          placeholder="搜索品牌名称" 
          v-model="searchQuery" 
          clearable
          size="small"
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button type="primary" size="small" @click="handleSearch" class="search-btn">
              <Search class="mr-1" /> 搜索
            </el-button>
          </template>
        </el-input>
        <!-- 修正：下拉框占位符改为“鞋类性别”，匹配筛选逻辑 -->
        <el-select 
          v-model="queryPageParam.bsex" 
          placeholder="请选择鞋类性别"
          @change="handleSearch"
          size="small"
          class="status-select"
        >
          <el-option 
            v-for="item in statusOptions" 
            :key="item.value" 
            :label="item.label || '全部性别'"  
            :value="item.value"
          />
        </el-select>
        <!-- 新增按钮添加图标，统一视觉 -->
        <el-button type="primary" size="small" @click="handleAddbrand" class="add-btn">
          <Plus class="mr-1" /> 新增品牌
        </el-button>
      </div>

      <!-- 品牌表格：修复笔误 border，空文本改为“暂无品牌数据” -->
      <el-table 
        :data="brandList" 
        style="width: 100%"
        border
        :header-cell-style="{ background: '#f0f5ff', color: '#409eff', fontWeight: '500', height: '50px' }"
        :row-class-name="tableRowClassName"
        @row-click="handleRowClick"
        highlight-current-row
        :empty-text="brandList.length === 0 ? '暂无品牌数据' : '加载中...'"
        class="brand-table"
        row-height="48"  
      >
        <el-table-column fixed prop="bid" label="ID" width="100" align="center" />
        <el-table-column fixed prop="bname" label="品牌名称" width="180" align="center" />
        <el-table-column prop="bsex" label="鞋类性别" width="180" align="center" />
        <!-- 优化：“是否上线”用标签显示，区分状态 -->
        <el-table-column prop="bstate" label="是否上线品牌" width="180" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.bstate === 1 ? 'success' : 'info'" effect="light">
              {{ scope.row.bstate === 1 ? '已上线' : '未上线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bremarks" label="备注" width="220" align="center">
          <!-- 备注过长时省略显示 -->
          <template #default="scope">
            <el-tooltip :content="scope.row.bremarks || '无备注'" placement="top">
              <span class="ellipsis-text">{{ scope.row.bremarks || '无备注' }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        
        <el-table-column fixed="right" label="操作" min-width="180" align="center">
          <template #default="scope">
         
            <el-button type="primary" size="small" @click="handleEdit(scope.row)" class="edit-btn">
              <Edit class="mr-1" /> 修改
            </el-button>
            <!-- 删除按钮弹出气泡确认框 -->
            <el-popconfirm 
              title="确定要删除此品牌吗?"
              confirm-button-text="是"
              cancel-button-text="否"
              icon-color="#ff4d4f"
              @confirm="handleDelete(scope.row.bid)"  
            >
              <template #reference>
                <el-button type="danger" size="small" class="delete-btn ml-2">
                  <Delete class="mr-1" /> 删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryPageParam.pageNum"
          v-model:page-size="queryPageParam.pageSize"
          :page-sizes="[5, 10, 20, 50]"
          :total="queryPageParam.recordCount"
          layout="total, sizes, prev, pager, next, jumper"
          background
          @size-change="querybrand"
          @current-change="querybrand"
          class="pagination"
        />
      </div>
    </el-card>
  </div>
   <!-- 新增/修改共用对话框 -->
  <el-dialog 
    :title="isEdit ? '修改品牌' : '新增品牌'"  
    v-model="showModal" 
    width="600px" 
    :center="true" 
    :close-on-click-modal="false" 
    :before-close="handClose"
  >
    <el-form 
      ref="brandForm"  
      :model="form" 
      :rules="formRules" 
      label-width="120px"
    >
      <!-- 隐藏的品牌ID（修改时需要） -->
      <el-form-item v-if="isEdit" prop="bid" hidden>
        <el-input v-model="form.bid" />
      </el-form-item>

      <!-- 品牌名称 -->
      <el-form-item label="品牌名称" prop="bname">
        <el-input 
          v-model="form.bname" 
          placeholder="请输入品牌名称" 
          maxlength="50" 
          show-word-limit 
        />
      </el-form-item>

      <!-- 鞋类性别 -->
      <el-form-item label="鞋类性别" prop="bsex">
        <el-select 
          v-model="form.bsex" 
          placeholder="请选择鞋类性别" 
          clearable
        >
          <el-option label="男" value="男" />
          <el-option label="女" value="女" />
        </el-select>
      </el-form-item>

      <!-- 是否上线 -->
      <el-form-item label="是否上线" prop="bstate">
        <el-radio-group v-model="form.bstate">
          <el-radio label="0">未上线</el-radio>
          <el-radio label="1">已上线</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 品牌备注 -->
      <el-form-item label="品牌备注" prop="bremarks">
        <el-input 
          v-model="form.bremarks" 
          type="textarea" 
          placeholder="请输入品牌备注" 
          rows="3" 
          maxlength="200" 
          show-word-limit 
        />
      </el-form-item>
    </el-form>

    <span class="dialog-footer">
      <el-button @click="handClose">取消</el-button>
      <el-button type="primary" @click="isEdit ? updateBrand() : saveBrand()">
        {{ isEdit ? '更新品牌' : '保存品牌' }}
      </el-button>
    </span>
  </el-dialog>
</template>
<style scoped>
/* 全局容器：优化背景色和内边距 */
.brand-management-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

/* 页面标题：增强视觉层次 */
.page-header {
  margin-bottom: 28px;
  color: #2d3748;
  padding-bottom: 12px;
  border-bottom: 1px solid #e2e8f0;
}

.page-header h1 {
  font-size: 26px;
  margin-bottom: 8px;
  font-weight: 600;
  color: #1a202c;
}

.page-header p {
  color: #718096;
  font-size: 14px;
  line-height: 1.5;
}

/* 卡片容器：优化阴影和圆角 */
.brand-table-card {
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  border-radius: 10px;
  overflow: hidden;
  transition: all 0.3s ease;
  background-color: #fff;
  margin-bottom: 20px;
}

.brand-table-card:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

/* 工具栏：优化布局和间距 */
.table-toolbar {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
  gap: 12px;
  flex-wrap: wrap;
}

/* 搜索框：调整宽度和样式 */
.search-input {
  width: 260px;
  flex-shrink: 0;
  ::v-deep .el-input__inner {
    border-radius: 6px 0 0 6px;
    height: 32px;
  }
}

/* 搜索按钮：优化圆角衔接 */
.search-btn {
  background-color: #409eff;
  color: #fff;
  border-radius: 0 6px 6px 0 !important;
  height: 32px;
  padding: 0 16px;
  &:hover {
    background-color: #66b1ff;
  }
}

/* 性别选择器：调整样式 */
.status-select {
  width: 160px;
  flex-shrink: 0;
  ::v-deep .el-select__inner {
    height: 32px;
    border-radius: 6px;
  }
}

/* 新增按钮：优化颜色 */
.add-btn {
  background-color: #67c23a;
  border-color: #67c23a;
  border-radius: 6px !important;
  height: 32px;
  padding: 0 16px;
  &:hover {
    background-color: #85ce61;
    border-color: #85ce61;
    transform: translateY(-1px);
  }
}

/* 品牌表格：优化内边距 */
.brand-table {
  margin: 0;
  ::v-deep .el-table__cell {
    padding: 12px 8px;
    font-size: 14px;
    color: #4a5568;
  }
  /* 表头文字对齐 */
  ::v-deep .el-table__header th {
    text-align: center !important;
  }
}

/* 表格行：优化奇偶行颜色 */
::v-deep .table-row-even {
  background-color: #fafbfc;
}

::v-deep .table-row-odd {
  background-color: #ffffff;
}

/* 行 hover 和选中效果：柔和过渡 */
::v-deep .el-table tr:hover > td {
  background-color: #f0f7ff !important;
  transition: background-color 0.2s ease;
}

::v-deep .el-table__row--current > td {
  background-color: #e6f4ff !important;
  border-color: #bfdbfe !important;
}

/* 状态标签：优化样式 */
::v-deep .el-tag--light {
  padding: 3px 10px;
  border-radius: 4px;
  font-size: 13px;
}

/* 操作按钮：统一样式和间距 */
::v-deep .detail-btn {
  background-color: #909399;
  border-color: #909399;
  border-radius: 4px !important;
  &:hover {
    background-color: #a6a9ad;
    border-color: #a6a9ad;
    transform: translateY(-1px);
  }
}

::v-deep .edit-btn {
  background-color: #409eff;
  border-color: #409eff;
  border-radius: 4px !important;
  &:hover {
    background-color: #66b1ff;
    border-color: #66b1ff;
    transform: translateY(-1px);
  }
}

::v-deep .delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
  border-radius: 4px !important;
  &:hover {
    background-color: #f78989;
    border-color: #f78989;
    transform: translateY(-1px);
  }
}

/* 备注过长省略：添加省略样式 */
.ellipsis-text {
  display: inline-block;
  width: 100%;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 分页容器：优化间距 */
.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 16px 20px;
  border-top: 1px solid #f0f2f5;
}

/* 分页组件：优化样式 */
.pagination {
  ::v-deep .el-pagination {
    font-size: 13px;
  }
  ::v-deep .el-pagination__total {
    margin-right: 12px;
    color: #718096;
  }
  ::v-deep .el-pagination__sizes {
    margin-right: 12px;
  }
  ::v-deep .el-pagination__button {
    border-radius: 4px;
    margin: 0 3px;
    color: #4a5568;
  }
  ::v-deep .el-pagination__button:hover {
    color: #409eff;
    border-color: #bfdbfe;
  }
  ::v-deep .el-pagination__current {
    background-color: #409eff;
    border-color: #409eff;
    border-radius: 4px;
  }
}

/* 响应式适配：优化小屏幕体验 */
@media (max-width: 1024px) {
  .search-input {
    width: 220px;
  }
}

@media (max-width: 768px) {
  .brand-management-container {
    padding: 12px;
  }
  
  .table-toolbar {
    gap: 8px;
    padding: 12px;
  }
  
  .search-input, .status-select {
    width: 100%;
  }
  
  .search-btn {
    border-radius: 6px !important;
    width: 100%;
    margin-top: 8px;
  }
  
  .add-btn {
    width: 100%;
    margin-top: 8px;
  }
  
  .pagination-container {
    justify-content: center;
    padding: 12px;
  }
  
  /* 表格固定列：小屏幕隐藏固定列，避免错乱 */
  ::v-deep .el-table__fixed,
  ::v-deep .el-table__fixed-right {
    display: none !important;
  }
}
</style>
